package com.tsingteng.cosfun.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Vibrator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLShortVideoComposer;
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.callback.OnRecyclerItemClickListener;
import com.tsingteng.cosfun.helper.RecyclerViewBugLayoutManager;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.costar.BeforeFilmActivity;
import com.tsingteng.cosfun.ui.costar.ComposeVideoActivity;
import com.tsingteng.cosfun.ui.costar.CostarActivity;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.Command;
import com.tsingteng.cosfun.utils.DesityUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.UIUtils;
import com.tsingteng.cosfun.utils.VideoOrderCommand;
import com.tsingteng.cosfun.widget.PressImageView;
import com.tsingteng.cosfun.widget.dialog.adapter.VideoOrderAdapter;

/**
 * 描述: 拖动页面
 * 创建人: 肖利
 * 时间: 2018/8/11
 * qq: (872179966)
 */

public class VideoOrderDialog implements View.OnClickListener {
    private static final String TAG = "OrderVideoDialog";
    private final int type;
    private Activity context;
    private Dialog dialog;
    private RecyclerView mRecyclerView;
    private PLShortVideoComposer mShortVideoComposer;
    private ItemTouchHelper mItemTouchHelper;
    private PressImageView repel;
    private PressImageView mIvNext;
    private VideoOrderAdapter videoOrderAdapter;
    private int starPosition = -1;

    public VideoOrderDialog(Activity context, int type) {
        this.context = context;
        this.type = type;
        initView();
    }

    private void initView() {
        dialog = new Dialog(context, R.style.dialog);
        dialog.setContentView(R.layout.dialog_order_video);
        mRecyclerView = dialog.findViewById(R.id.rv_order_rv);
        repel = dialog.findViewById(R.id.repel);
        mIvNext = dialog.findViewById(R.id.iv_next);
        repel.setOnClickListener(this);
        mIvNext.setOnClickListener(this);
        dialog.findViewById(R.id.iv_play).setOnClickListener(this);
        dialog.findViewById(R.id.iv_back).setOnClickListener(this);
        RecyclerViewBugLayoutManager mLayoutManager = new RecyclerViewBugLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        videoOrderAdapter = new VideoOrderAdapter(VideoHelper.getIntence().getVideoSectionBeanList(), context);
        mRecyclerView.setAdapter(videoOrderAdapter);
        mRecyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecyclerView) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {

            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //判断被拖拽的是否是前两个，如果不是则执行拖拽
                mItemTouchHelper.startDrag(vh);
                //获取系统震动服务
                Vibrator vib = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);//震动70毫秒
                if (vib != null) {
                    vib.vibrate(70);
                }
            }

        });
        progressDialog = new ProgressDialog(context);
        dialog.setOnDismissListener(dialog -> {
            if (type == 1) {
                ((CostarActivity) context).showSliceSelectDialog();
            } else {
                ((BeforeFilmActivity) context).showSliceSelectDialog();
            }

        });

        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
//                if (fromPosition < toPosition) {
//                    for (int i = fromPosition; i < toPosition; i++) {
//                        Collections.swap(VideoHelper.getIntence().getVideoSectionBeanList(), i, i + 1);
//                    }
//                } else {
//                    for (int i = fromPosition; i > toPosition; i--) {
//                        Collections.swap(VideoHelper.getIntence().getVideoSectionBeanList(), i, i - 1);
//                    }
//                }
                videoOrderAdapter.notifyItemMoved(fromPosition, toPosition);
                Log.e(TAG, "onMove+ fromPosition==>" + fromPosition + "toPosition ====>" + toPosition);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

            /**
             * 长按选中Item的时候开始调用
             */
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
//                    Toast.makeText(context, "ACTION_STATE_IDLE+++++++>"+ viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
                    starPosition = viewHolder.getAdapterPosition();
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            /**
             * 手指松开的时候还原
             */
            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(0);
//                Toast.makeText(context, "clearView+++++++>"+ viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
                int endPosition = viewHolder.getAdapterPosition();
                if (starPosition != -1) {
                    VideoOrderCommand videoOrderCommand = new VideoOrderCommand(starPosition, endPosition);
                    VideoHelper.getIntence().getCommendManger().pushCommandAndApply(videoOrderCommand);
                }
                refreshData();
            }
        });
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.setAdapter(this.videoOrderAdapter);
        //拼接
        mShortVideoComposer = new PLShortVideoComposer(context);
    }


    public void show() {
        Window window = dialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.CENTER);
            window.setLayout(AppUtils.getScreenWidthAndHeight(context)[0] - DesityUtils.dp2px(30), ViewGroup.LayoutParams.WRAP_CONTENT);
            dialog.show();
        }

    }

    public void dissMiss() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.repel:
                Command undo = VideoHelper.getIntence().getCommendManger().undo();
                if (undo == null) {
                    AppUtils.showHintDialogToast(context, "撤销失败");
                    return;
                }
                VideoHelper.getIntence().getOperationPosition(1, context, undo);
                refreshData();
                break;
            case R.id.iv_next:
                Command redo = VideoHelper.getIntence().getCommendManger().redo();
                if (redo == null) {
                    AppUtils.showHintDialogToast(context, "恢复失败");
                    return;
                }
                VideoHelper.getIntence().getOperationPosition(2, context, redo);
                refreshData();
                break;
            case R.id.iv_play:
                toPlayToGether();
                break;

            case R.id.iv_back:
                dialog.dismiss();
                break;

        }
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        if (VideoHelper.getIntence().getCommendManger().isCanUndo()) {
            repel.setEnabled(true);
            repel.setImageDrawable(context.getResources().getDrawable(R.drawable.previous_black_icon));
        } else {
            repel.setEnabled(false);
            repel.setImageDrawable(context.getResources().getDrawable(R.drawable.previous_black_icon_nopress));
        }
        if (VideoHelper.getIntence().getCommendManger().isCanRedo()) {
            mIvNext.setEnabled(true);
            mIvNext.setImageDrawable(context.getResources().getDrawable(R.drawable.next_step_black_icon));
        } else {
            mIvNext.setEnabled(false);
            mIvNext.setImageDrawable(context.getResources().getDrawable(R.drawable.next_step_black_icon_nopress));
        }
        videoOrderAdapter.notifyDataSetChanged();
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    private void toPlayToGether() {
        VideoHelper.getIntence().clearEmptyVideoPath();
        if (VideoHelper.getIntence().getVideoPathList().size() <= 0) {
            new ContentDialog(context).setContent("请先添加一个视频片段!").setAffirmContent("我知道了!").setOnOneClickListener(() -> {
            }).show();
            return;

        }
        onDone();
    }

    private ProgressDialog progressDialog;

    /**
     * 开始拼接
     */
    private void onDone() {
        if (VideoHelper.getIntence().getVideoPathList().size() <= 1) {
            Intent intent = new Intent(context, ComposeVideoActivity.class);
            intent.putExtra(VideoHelper.VIDEO_PATH, VideoHelper.getIntence().getVideoPathByIndex(0));
            context.startActivity(intent);
            context.overridePendingTransition(R.anim.activity_up, R.anim.activity_down);
        } else {
            PLAudioEncodeSetting plAudioEncodeSetting = new PLAudioEncodeSetting();
            PLVideoEncodeSetting setting = new PLVideoEncodeSetting(context);
            setting.setEncodingSizeLevel(PLVideoEncodeSetting.VIDEO_ENCODING_SIZE_LEVEL.VIDEO_ENCODING_SIZE_LEVEL_480P_3);
            setting.setEncodingBitrate(VideoHelper.mEncodingBitrate);
            setting.setEncodingFps(22);
            plAudioEncodeSetting.setHWCodecEnabled(true);
            if (mShortVideoComposer.composeVideos(VideoHelper.getIntence().getVideoPathList(), VideoHelper.VIDEO_COMPOSED + System.currentTimeMillis() + "compose.mp4", setting, mVideoSaveListener)) {
                if (progressDialog == null) progressDialog = new ProgressDialog(context);
                progressDialog.show();
                if (type == 1) {
                    ((CostarActivity) context).dissSliceSelectDialog();
                } else {
                    ((BeforeFilmActivity) context).dissSliceSelectDialog();
                }
            }


        }

    }


    private PLVideoSaveListener mVideoSaveListener = new PLVideoSaveListener() {
        @Override
        public void onSaveVideoSuccess(final String destFile) {
            UIUtils.runOnUIThread(() -> {
                progressDialog.disMissDialog();
                Intent intent = new Intent(context, ComposeVideoActivity.class);
                intent.putExtra(VideoHelper.VIDEO_PATH, destFile);
                context.startActivity(intent);
                context.overridePendingTransition(R.anim.activity_up, R.anim.activity_down);
                dissMiss();
            });
        }

        @Override
        public void onSaveVideoFailed(int errorCode) {
            progressDialog.disMissDialog();
        }

        @Override
        public void onSaveVideoCanceled() {
            progressDialog.disMissDialog();
        }


        @Override
        public void onProgressUpdate(final float percentage) {
            UIUtils.runOnUIThread(() -> {
                LogUtils.i("onProgressUpdate" + percentage);
                if ((int) (percentage * 100) <= 100) {
                    progressDialog.setmProgressbar((int) (percentage * 100));
                }
            });
        }
    };


}
